<?php

namespace Beerus\Modules\DecoCalculator\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecoCalculator\DecoCalculatorArtificial as mDecoCalculatorArtificial;
use Illuminate\Support\MessageBag;
use Doraemon\service\DecorationCalculator\GetCountPrice;

class ArtificialController
{
    // 列表
    public function index(Request $request,Content $content) {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->all();

        $conditions = [
            'data_status' => mDecoCalculatorArtificial::STATUS_NORMAL,
        ];

        if (!empty($params['living_space'])) {
            $conditions['living_space'] = $params['living_space'];
        }

        if (!empty($params['project'])) {
            $conditions['project'] = $params['project'];
        }

        if (!empty($params['project_name'])) {
            $conditions['project_name[~]'] = '%' . $params['project_name'] . '%';
        }

        $total = mDecoCalculatorArtificial::countByCondition($conditions);

        $conditions['ORDER'] = ['living_space' => 'ASC','project' => 'ASC', 'sort' => 'ASC'];
        $conditions['LIMIT'] = [($page - 1) * $pageSize, $pageSize ];

        $list = mDecoCalculatorArtificial::listByCondition($conditions);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('living_space', '居室空间')->select(mDecoCalculatorArtificial::ALL_SPACE_MAP);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('project', '项目')->select(mDecoCalculatorArtificial::ALL_PROJECT_MAP);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('project_name', '细项名称')->placeholder('细项名称');
                    });

                    $filter->expand();
                });

                $grid->column("id", 'ID');
                $grid->column("living_space", '居室空间')->display(function () {
                    return mDecoCalculatorArtificial::ALL_SPACE_MAP[$this->living_space];
                });
                $grid->column("project", '项目')->display(function () {
                    return mDecoCalculatorArtificial::ALL_PROJECT_MAP[$this->project];
                });
                $grid->column("project_name", '细项名称');
                $grid->column("quantities", '工程量')->display(function () {
                    return mDecoCalculatorArtificial::QUANTITIES_MAP[$this->quantities];
                });
                $grid->column("quantities_coefficient", '工程量系数')->display(function () {
                    return preg_replace('/.00/', '', $this->quantities_coefficient);
                });
                $grid->column("unit_price", '单价')->display(function () {
                    return $this->unit_price/100;
                });
                $grid->column("deco_specs", '规格')->display(function () {
                    $specs_arr = array_map(function ($v) {
                        return mDecoCalculatorArtificial::DECO_SPECS_MAP[$v];
                    }, explode(',', $this->deco_specs));
                    return implode(' ', $specs_arr);
                });
                $grid->column("sort", '排序');
                $grid->column("edit_time", '修改时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                });
            });

        $tab = new Tab();
        $tab->add('人工费配置列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('人工费配置列表')
            ->description(' ')
            ->breadcrumb(['text' => '人工费配置列表']);
    }

    // 编辑
    public function edit(Content $content, $id = 0)
    {
        if($id == 0) {
            return $content
                ->header('人工费配置 - 新增')
                ->breadcrumb([
                    'text' => '人工费配置列表',
                    'url' => '/DecoCalculator/artificial/',
                ])
                ->body(self::editAction($id));
        } else {
            return $content
                ->header('人工费配置 - 编辑')
                ->breadcrumb([
                    'text' => '人工费配置列表',
                    'url' => '/DecoCalculator/artificial/',
                ])
                ->body(self::editAction($id));
        }
    }

    public function editAction($id)
    {
        $script = <<<SCRIPT
            $(document).ready(function(){  
                $('label[for="project"]').addClass('asterisk');//增加一个class
            });
SCRIPT;
        Admin::script($script);

        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = mDecoCalculatorArtificial::getByCondition(['id' => $id]);
            $data['unit_price'] = $data['unit_price']/100;
            $data['quantities_coefficient'] = preg_replace('/.00/', '', $data['quantities_coefficient']);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->select('living_space', '居室空间')->options(mDecoCalculatorArtificial::LIVING_SPACE_MAP + mDecoCalculatorArtificial::OTHER_SPACE_MAP)
            ->when('in', array_keys(mDecoCalculatorArtificial::LIVING_SPACE_MAP), function (Form $form) {
                $form->select('project', '项目')->options(mDecoCalculatorArtificial::LIVING_PROJECT_MAP)->setWidth(4, 2);
            })->when('in', array_keys(mDecoCalculatorArtificial::OTHER_SPACE_MAP), function (Form $form) {
                $form->select('project', '项目')->options(mDecoCalculatorArtificial::OTHER_PROJECT_MAP)->setWidth(4, 2);
            })
            ->required()->setWidth(4, 2);

        $form->text('project_name', '细项名称')->required()->attribute('maxlength', 7)->setWidth(4, 2)->help("最长7个汉字且同一空间的项目内不能重名");
        $form->select('quantities', '工程量')->options(mDecoCalculatorArtificial::QUANTITIES_MAP)->required()->setWidth(4, 2);
        $form->text('quantities_coefficient', '工程量系数')->pattern('^([0-9]){1,7}(.[0-9]{1,2})?$')->required()->setWidth(4, 2)->help("请填写非零整数及小数点后两位");
        $form->text('unit_price', '单价')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2)->help("请填写正整数");
        $form->multipleSelect('deco_specs', '装修规格')->options(mDecoCalculatorArtificial::DECO_SPECS_MAP)->required()->setWidth(4, 2);
        $form->text('sort', '排序')->pattern('^([1-9][0-9]*){1,10}$')->required()->setWidth(4, 2)->help("请填写正整数");
        $form->action('/admin/DecoCalculator/artificial/save');
        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        try {
            $params = $request->all();
            if (empty($params['project'])) {
                throw new \Exception("项目不能为空");
            }

            // 验证同一空间同一项目内
            $conditions = [
                'living_space' => $params['living_space'],
                'project' => $params['project'],
            ];

            if ($params['id']) {
                $conditions['id[!]'] = $params['id'];
            }

            // 细项名称不能重复
            $project_name_con = array_merge($conditions, ['project_name' => $params['project_name']]);
            $project_name = mDecoCalculatorArtificial::getByCondition($project_name_con);
            if ($project_name) {
                throw new \Exception("该空间的项目内细项名称已存在，请勿重复添加");
            }

            // 排序不能重复
            $sort_con = array_merge($conditions, ['sort' => $params['sort']]);
            $sort = mDecoCalculatorArtificial::getByCondition($sort_con);
            if ($sort) {
                throw new \Exception("该空间的项目内排序值已存在，请勿重复添加");
            }

            $data = [
                'living_space' => $params['living_space'],
                'project' => $params['project'],
                'project_name' => $params['project_name'],
                'quantities' => $params['quantities'],
                'quantities_coefficient' => $params['quantities_coefficient'],
                'unit_price' => $params['unit_price'] * 100,
                'deco_specs' => implode(',', array_filter($params['deco_specs'])),
                'sort' => $params['sort'],
                'admin_id' => Admin::user()->id,
            ];

            if ($params['id']) {
                $data['edit_time'] = time();
                mDecoCalculatorArtificial::updateInfo($data, [
                    'id' => $params['id']
                ]);

                $title = '修改成功';
                //清除计算器的数据缓存
                GetCountPrice::delCountPriceData();
            } else {
                $data['add_time'] = time();
                mDecoCalculatorArtificial::addInfo($data);

                $title = '添加成功';
                //清除计算器的数据缓存
                GetCountPrice::delCountPriceData();
            }

            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/DecoCalculator/artificial')->with(compact('success'));

        }  catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delete($id)
    {
        $update_data = [
            'data_status' => mDecoCalculatorArtificial::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (!mDecoCalculatorArtificial::updateInfo($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
        //清除计算器的数据缓存
        GetCountPrice::delCountPriceData();
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }
}
